package com.property.manage.service.system;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guardchina.framework.auth.jwt.JsonWebToken;
import com.guardchina.framework.mybatis.model.CustomPage;
import com.guardchina.framework.util.exception.BusinessException;
import com.guardchina.framework.util.exception.SystemException;
import com.guardchina.framework.web.model.UserFeature;
import com.property.manage.dao.system.UserMapper;
import com.property.manage.model.system.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 描述
 *
 * @author lwb
 * @since 2020/7/15
 */
@Component
@Slf4j
public class UserService {

    private UserMapper userMapper;
    private RoleMenuService roleMenuService;
    private MenuService menuService;
    private JsonWebToken jwt;
    private RoleService roleService;


    public User findUser(Integer userId){
        return userMapper.selectById(userId);
    }

    public User getUser(Integer userId){
        User user = findUser(userId);

        return Optional.ofNullable(user).orElseThrow(() -> new SystemException("账号不存在", String.format("userId[%s]", userId)));
    }


    public void deleteUserRole(Integer roleId){
        UpdateWrapper<User> wrapper = new UpdateWrapper<>();
        wrapper.set("role_id", null);
        wrapper.eq("role_id", roleId);
        userMapper.update(null, wrapper);
    }

    public CustomPage<UserDetail> userPage(Long pageNo, Long pageSize, String userName){
        Page<UserDetail> page = new Page<>(pageNo, pageSize);

        IPage<UserDetail> result = userMapper.getUserDetails(page, userName);

        return new CustomPage<>(result);
    }


    public void add(String userName, String pwd, Integer roleId, String mobile){
        User user = findByName(userName);
        if(user != null){
            throw new BusinessException("该账号已存在", String.format("userName[%s]", userName));
        }

        user = new User();

        user.setUserName(userName);
        user.setPwd(pwd);
        user.setMobile(mobile);
        user.setRoleId(roleId);

        userMapper.insert(user);
    }

    public void update(Integer userId, String userName, String pwd, Integer roleId, String mobile){
        User user = findByName(userName);
        if(user != null && !user.getUserId().equals(userId)){
            throw new BusinessException("该账号已存在", String.format("userName[%s]", userName));
        }

        UpdateWrapper<User> wrapper = new UpdateWrapper<>();
        wrapper.set(StringUtils.isNotBlank(userName), "user_name", userName);
        wrapper.set(StringUtils.isNotBlank(pwd), "pwd", pwd);
        wrapper.set("mobile", mobile);
        wrapper.set("role_id", roleId);
        wrapper.eq("user_id", userId);

        userMapper.update(null, wrapper);
    }

    public void delete(Integer userId){
        userMapper.deleteById(userId);
    }

    public UserLoginInfo login(String userName, String pwd){
        User user = findByName(userName);
        if(user == null){
            throw new BusinessException("账号不存在", String.format("userName[%s]", userName));
        }

        if(!user.getPwd().equals(pwd)){
            throw new BusinessException("密码不正确", String.format("userName[%s],dbPwd[%s],pwd[%s]", userName, user.getPwd(), pwd));
        }

        Role role = roleService.findRole(user.getRoleId());

        UserLoginInfo userLoginInfo = new UserLoginInfo();
        userLoginInfo.setToken(createToken(user));
        userLoginInfo.setUserName(user.getUserName());
        userLoginInfo.setRoleName(Optional.ofNullable(role).map(Role::getRoleName).orElse(null));
        userLoginInfo.setMenus(getUserMenu(user));

        return userLoginInfo;
    }

    private String createToken(User user){
        UserFeature userFeature = new UserFeature();
        userFeature.setUserKey(user.getUserId().toString());
        userFeature.setCreateTime(System.currentTimeMillis());

        return jwt.createToken(userFeature);
    }


    private User findByName(String userName){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name", userName);
        return userMapper.selectOne(wrapper);
    }


    private List<MenuVo> getUserMenu(User user){
        Optional.ofNullable(user).orElseThrow(() -> new SystemException("用户不能为空"));

        List<RoleMenu> roleMenus = roleMenuService.getRoleMenus(user.getRoleId());
        if(CollectionUtils.isEmpty(roleMenus)){
            return null;
        }

        List<Menu> menus = menuService.getMenus(roleMenus.stream().map(RoleMenu::getMenuId).collect(Collectors.toSet()));



        return menuService.convertToMenuVo(menus);
    }


    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }
    @Autowired
    public void setRoleMenuService(RoleMenuService roleMenuService) {
        this.roleMenuService = roleMenuService;
    }
    @Autowired
    public void setMenuService(MenuService menuService) {
        this.menuService = menuService;
    }
    @Autowired
    public void setJwt(JsonWebToken jwt) {
        this.jwt = jwt;
    }
    @Autowired
    public void setRoleService(RoleService roleService) {
        this.roleService = roleService;
    }
}
